<template>
  <div class="pro-table">
    <Card v-if="searchForm && searchForm.length" dis-hover>
      <SearchFormBar
        ref="search-form"
        :list="searchForm"
        @search="onSearch"
        @valueInited="onValueInined"
      />
    </Card>
    <div class="pro-table__body">
      <Card :title="title" dis-hover>
        <template>
          <slot name="extra"></slot>
        </template>
        <Table
          v-loading="loading"
          :border="border"
          :columns="columns"
          :data="tableData"
          size="small"
          :show-summary="showSummary"
          @on-selection-change="selectChange"
          ref="tableData"
        />
        <Page v-if="pagination"
              v-bind="mergedPagination"
              @on-change="handleCurrentChange"
              @on-page-size-change="handleSizeChange"
              :show-total="true"
              class="pro-table__page" />
      </Card>
    </div>
  </div>
</template>

<script>
import { isFunction } from 'lodash';
import SearchFormBar from '../SearchFormBar';

export default {
  name: 'ProTable',
  components: {
    SearchFormBar
  },
  props: {
    // 是否显示搜索
    // showSearch: Boolean,
    // 查询表单
    searchForm: {
      type: Array,
      default: () => []
    },
    // 搜索之前对参数进行一些修改
    beforeSearchSubmit: {
      type: Function,
      default: null
    },
    // 表格头部标题
    title: String,
    // 表格是否显示边框
    border: {
      type: Boolean,
      default: true
    },
    // 表格列配置
    columns: {
      type: Array,
      default: () => []
    },
    // 分页配置 见view-design Page组件
    pagination: {
      type: [Object, Boolean],
      default: () => {}
    },
    // 请求数据方法
    request: {
      type: Function
    },
    // 请求成功回调
    onRequestSuccess: {
      type: Function,
      default: null
    },
    // 选中改变出发
    onSelectChange: {
      type: Function,
      default: null
    },
    // 请求失败回调
    onRequestError: {
      type: Function,
      default: null
    },
    // 指定table数据对应接口返回值的key
    listKey: {
      type: String,
      default: 'list'
    },
    // 是否立即调用接口
    immediate: {
      type: Boolean,
      default: false
    },
    // 显示合计
    showSummary: Boolean
  },
  data() {
    return {
      loading: false,
      tableData: [],
      paginationConfig: {
        pageSize: 20,
        showSizer: true,
        pageSizeOpts: [10, 20, 30, 40, 100]
      },
      searchParams: {
        currentPage: 1,
        pageSize: 20
      },
      selectList:[],
      mergedPagination: {}
    };
  },
  watch: {
    pagination: {
      handler: 'setPaginationConfig',
      immediate: true,
      deep: true
    }
  },
  async created() {
    // this.searchParams = this.getSearchForm(this.searchForm);
    if (this.immediate) {
       await this.fetchData();
      //this.$refs['search-form'].
    }
  },
  methods: {
    onSearch(options = {}) {
      this.searchParams = { ...this.searchParams, ...options };
      this.searchParams.currentPage = 1;
      this.mergedPagination.current = 1;
      this.fetchData();
    },
    selectChange(rows){
      if(this.onSelectChange){
        this.onSelectChange(rows)
      }
    },
    getSearchParams(){
     return this.$refs['search-form'].getSearchParams()
    },
    setPaginationConfig() {
      if (!this.pagination){
        this.mergedPagination = this.paginationConfig;
      }
      this.mergedPagination = { ...this.paginationConfig, ...this.pagination };
      console.log('setPaginationConfig page config change:',this.mergedPagination)
    },
    onValueInined(values) {
      if (this.immediate) this.onSearch(values);
    },
    handleSizeChange(size) {
      const newPage = 1;
      const newPageSize = size;
      this.mergedPagination.current = newPage;
      this.mergedPagination.pageSize = newPageSize;
      this.searchParams.pageSize = newPageSize;
      this.searchParams.currentPage = newPage;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.mergedPagination.current = page;
      this.searchParams.currentPage = page;
      this.fetchData();
    },
    exportLocalCsv(name){

      this.$refs.tableData.exportCsv({
        filename: name,
        original: false
      });
    },
    async fetchData() {
      if (!this.request) return;

      this.loading = true;
      let searchParams = { ...this.searchParams };
      if (isFunction(this.beforeSearchSubmit)) {
        searchParams = this.beforeSearchSubmit(searchParams);
      }
      const result = await this.request(searchParams);
      this.loading = false;
      let res = (result && result.data) || {};
      if (!res) {
        this.$Message.error('请求发生错误~');
        return;
      }
      const { ret, data = {}, msg } = res;
      if(ret!==undefined){
        if (ret === 0) {
        this.tableData = data[this.listKey] || [];
        this.mergedPagination.total =
          (data.pagination && data.pagination.total) || 0;
        if (isFunction(this.onRequestSuccess)) {
          this.onRequestSuccess(res);
        }
      } else {
        this.tableData = [];
        if (isFunction(this.onRequestError)) {
          this.onRequestError(res);
        } else {
          this.$Message.error(msg || '发生错误~');
        }
      }
      }
    }
  }
};
</script>

<style lang="less">
.pro-table {
  &__search {
    .ivu-card-body {
      padding-bottom: 0;
    }
  }
  &__body {
    margin-top: 16px;
    .ivu-card-extra + .ivu-card-body {
      margin-top: 46px;
    }
  }
  &__page {
    margin-top: 10px;
    text-align: right;
  }
}
</style>
